import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Select,
  Input,
  Switch,
  message,
  Popconfirm,
  List,
} from "antd";
import { EditOutlined, PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { auth } from "@/utils/auth";
import styles from "./index.less";
import moment from "moment";

interface TaskData {
  id: string;
  type: string;
  title: string;
  status: string;
  createdAt: string;
  taskCategoryId: string;
}

interface TaskType {
  id: string;
  name: string;
  createdAt: string;
}

const TasksPage: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isTypeModalVisible, setIsTypeModalVisible] = useState(false);
  const [createForm] = Form.useForm();
  const [typeForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<TaskData[]>([]);
  const [taskTypes, setTaskTypes] = useState<TaskType[]>([]);
  const [typeLoading, setTypeLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取任务列表数据
  const fetchTaskList = async (page: number = pagination.current) => {
    try {
      setLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pagination.pageSize.toString(),
      });

      const response = await fetch(
        `/agentapi/tasks?${queryParams.toString()}`,
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        if (result && result.data && Array.isArray(result.data)) {
          const formattedData = result.data.map((item: any) => ({
            id: item.id,
            type: item.type,
            title: item.title,
            status: item.status,
            createdAt: item.createdAt,
            taskCategoryId: item.taskCategoryId,
          }));

          setData(formattedData);
          setPagination({
            current: page,
            pageSize: pagination.pageSize,
            total: result.pagination?.total || 0,
          });
        }
      } else {
        message.error("获取任务列表失败");
      }
    } catch (error) {
      message.error("获取任务列表失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  // 获取任务类型列表
  const fetchTaskTypes = async () => {
    try {
      setTypeLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/task-categories", {
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 200) {
        const result = await response.json();
        setTaskTypes(result.data);
      } else {
        message.error("获取任务类型列表失败");
      }
    } catch (error) {
      message.error("获取任务类型列表失败，请检查网络连接");
    } finally {
      setTypeLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchTaskList(1);
    fetchTaskTypes();
  }, []);

  const handleDelete = async (record: TaskData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/tasks/${record.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 204) {
        message.success("删除成功");
        fetchTaskList(pagination.current); // 重新获取当前页数据
      } else {
        message.error("删除失败");
      }
    } catch (error) {
      message.error("删除失败，请检查网络连接");
    }
  };

  const handleStatusChange = async (checked: boolean, record: TaskData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/tasks/${record.id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({
          status: checked ? "removed" : "not_start",
        }),
      });

      if (response.status === 200) {
        message.success(`修改成功`);
        fetchTaskList(pagination.current); // 重新获取当前页数据
      } else {
        message.error("操作失败");
      }
    } catch (error) {
      message.error("操作失败，请检查网络连接");
    }
  };

  const handleCreate = async () => {
    try {
      const values = await createForm.validateFields();
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/tasks", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({
          type: "global",
          title: values.title,
          taskCategoryId: values.taskCategoryId,
        }),
      });

      if (response.status === 201) {
        message.success("发布成功");
        setIsModalVisible(false);
        createForm.resetFields();
        fetchTaskList(1); // 创建成功后返回第一页
      } else {
        message.error("发布失败");
      }
    } catch (error) {
      message.error("发布失败，请检查网络连接");
    }
  };

  const columns: ColumnsType<TaskData> = [
    {
      title: "任务类型",
      dataIndex: "taskCategoryId",
      key: "taskCategoryId",
      render: (taskCategoryId) => {
        const taskType = taskTypes.find((type) => type.id === taskCategoryId);
        return taskType ? taskType.name : "未知";
      },
    },
    {
      title: "任务名称",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      key: "status",
      render: (_, record) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <Switch
            checked={record.status === "removed" ? true : false}
            onChange={(checked) => handleStatusChange(checked, record)}
            style={{ margin: "0 5px" }}
          />
          {record.status === "removed" ? "已删除" : "未开始"}
        </div>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (createdAt) => {
        return moment.utc(createdAt).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      title: "操作",
      key: "operation",
      render: (_, record) => (
        <Popconfirm
          title="删除任务"
          description="确定要删除这个任务吗？此操作不可恢复。"
          onConfirm={() => handleDelete(record)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    createForm.resetFields();
  };

  const showTypeModal = () => {
    setIsTypeModalVisible(true);
    fetchTaskTypes();
  };

  const handleTypeCancel = () => {
    setIsTypeModalVisible(false);
    typeForm.resetFields();
  };

  const handleAddType = async (values: { type: string }) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/task-categories", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({ name: values.type }),
      });

      if (response.status === 201) {
        message.success("添加成功");
        typeForm.resetFields();
        fetchTaskTypes(); // 重新加载列表
      } else {
        message.error("添加失败");
      }
    } catch (error) {
      message.error("添加失败，请检查网络连接");
    }
  };

  const handleDeleteType = async (type: TaskType) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/task-categories/${type.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 204) {
        message.success("删除成功");
        fetchTaskTypes(); // 重新加载列表
      } else if (response.status === 409) {
        message.error("删除失败,该类型下有任务。");
      } else {
        message.error("删除失败");
      }
    } catch (error) {
      message.error("删除失败，请检查网络连接");
    }
  };

  return (
    <div className={styles.container}>
      <Card>
        <div className={styles.tableHeader}>
          <Button
            type="primary"
            icon={<EditOutlined />}
            style={{ marginRight: "16px" }}
            onClick={showTypeModal}
          >
            任务类型管理
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
            发布任务
          </Button>
        </div>

        <Table<TaskData>
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          style={{
            height: `calc(100vh - 260px)`,
            overflow: "auto",
            scrollbarWidth: "none",
          }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            // showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page) => fetchTaskList(page),
          }}
        />

        <Modal
          title="发布任务"
          open={isModalVisible}
          onOk={handleCreate}
          onCancel={handleCancel}
          confirmLoading={loading}
          okText="确定"
          cancelText="取消"
        >
          <Form
            form={createForm}
            layout="horizontal"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
          >
            <Form.Item
              name="taskCategoryId"
              label="任务类型"
              rules={[{ required: true, message: "请选择任务类型" }]}
            >
              <Select>
                {taskTypes.map((taskCategoryId) => (
                  <Select.Option
                    key={taskCategoryId.id}
                    value={taskCategoryId.id}
                  >
                    {taskCategoryId.name}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="title"
              label="具体任务"
              rules={[{ required: true, message: "请输入具体任务" }]}
            >
              <Input placeholder="请输入具体任务" />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="任务类型管理"
          open={isTypeModalVisible}
          onCancel={handleTypeCancel}
          footer={null}
        >
          <Form form={typeForm} layout="horizontal" onFinish={handleAddType}>
            <Form.Item
              name="type"
              rules={[
                { required: true, message: "请输入任务类型" },
                { max: 10, message: "不能超过10个字" },
              ]}
            >
              <Input.Search
                placeholder="请输入任务类型"
                enterButton="添加"
                onSearch={() => typeForm.submit()}
              />
            </Form.Item>
          </Form>
          <List
            loading={typeLoading}
            dataSource={taskTypes}
            renderItem={(type) => (
              <List.Item
                actions={[
                  <Popconfirm
                    key="delete"
                    title="删除任务类型"
                    description="确定要删除这个任务类型吗？如果该类型下有任务，将无法删除。"
                    onConfirm={() => handleDeleteType(type)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button type="link" danger>
                      删除
                    </Button>
                  </Popconfirm>,
                ]}
              >
                {type.name}
              </List.Item>
            )}
          />
        </Modal>
      </Card>
    </div>
  );
};

export default TasksPage;
